package com.changgou.auth.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.user.feign.UserFeign;
import com.changgou.user.pojo.User;
import com.changgou.user.utils.SMSUtils;
import com.changgou.user.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PasswordEncoder passwordEncoder;

    private static final String REDISTER_CODE_ = "redister_code_";

    @RequestMapping("/toregisterpage")
    public String toregisterpage(){
        return "register";
    }

    @RequestMapping("/send_sms")
    @ResponseBody
    public Result sendmessage(@RequestParam("mobile") String mobile){
        Map map = new HashMap();
        map.put("phone",mobile);
        Result<List<User>> result = userFeign.findList(map);//查询电话用户是否存在，存在则不予发送短信
        List<User> users = result.getData();
        System.out.println(users);
        if (result.getData()!=null && users.size()>0){
            return new Result(false, StatusCode.ERROR,"号码已被注册过，不能重复注册");
        }else {
            //生成验证码
            Integer validateCode = ValidateCodeUtils.generateValidateCode(4);
            System.out.println("验证码："+validateCode);
            try {
                //SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, mobile, validateCode.toString());
                //将短信保存在redis中5分钟
                redisTemplate.opsForValue().set(REDISTER_CODE_+mobile,validateCode.toString());
                redisTemplate.expire(REDISTER_CODE_+mobile,5, TimeUnit.MINUTES);//保存5分钟
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false, StatusCode.ERROR,"验证码发送失败");
            }
            return new Result(true,StatusCode.OK,"发送消息成功");
        }
    }

    @PostMapping("/add")
    @ResponseBody
    public Result register(@RequestParam("smsCode") String smsCode,@RequestBody Map map){
        //获取验证码和缓存的比对
        String mobile = (String)map.get("phone");
        String redisCode = (String)redisTemplate.boundValueOps(REDISTER_CODE_ + mobile).get();
        System.out.println("redis缓存验证码："+redisCode);;
        if (smsCode!=null&&redisCode!=null&&smsCode.equals(redisCode)){
            //验证码输入正确
            String password = (String) map.get("password");
            password = passwordEncoder.encode(password);
            System.out.println("编码后号码为"+mobile+"的密码是："+password);
            //用户设置
            User user = new User();
            user.setUsername(mobile);
            user.setPassword(password);
            user.setCreated(new Date());
            user.setUpdated(new Date());
            user.setIsMobileCheck("1");
            user.setPhone(mobile);
            user.setPoints(0);
            user.setStatus("1");
            user.setIsEmailCheck("0");
            //远程调用添加用户
            userFeign.add(user);
            return new Result(true,StatusCode.OK,"注册成功");
        }
        else {
            return new Result(false,StatusCode.ERROR,"注册失败，验证码错误");
        }
    }
}
